<?php
require_once __DIR__ . '/vendor/autoload.php';
use lttxws\JT808;
use lttxws\JT808_0100;
use lttxws\JT808_0102;
use Workerman\Worker;

// 创建一个Worker监听8095端口，不使用任何应用层协议
//$tcp_worker = new Worker("tcp://192.168.1.5:8095");
$tcp_worker = new Worker("tcp://192.168.61.131:8095");
// 启动12个进程对外提供服务
$tcp_worker->count = 12;

$tcp_worker->onWorkerStart = function($worker)
{
    // 将db实例存储在全局变量中(也可以存储在某类的静态成员中)
    global $db;
    $db = new \Workerman\MySQL\Connection('192.168.61.131', '3306', 'rsuser', '123456', 'jt808');
};

// 当客户端发来数据时
$tcp_worker->onMessage = function ($connection, $data) {
    
    global $db;
    
    $JT808 = new JT808();
	//16进制数据
	$data16Arrays = $JT808->getTo16Bytes($data);
	
	$now = date('Y-m-d H:i:s');
	
	foreach ($data16Arrays as $key => $data16Array) {
		//获取消息id
	    $MessageId = $JT808->getMessageIdNumber($data16Array);
		//设备号
	    $equipmentNumber = $JT808->getEquipmentNumber($data16Array);
	    
	    echo "\r\n MessageId: {$MessageId} result  \r\n";
	    
	    // 插入终端请求日志
	    $db->insert('request_log')->cols(array(
	        'phone'        => $equipmentNumber,
	        'message_id'   => $MessageId,
	        'data'         => implode("",$data16Array),
	        'ctime'        => $now))->query();
	    
	    $ret = '00';   //应答结果
	    
	    //终端注册
	    if($MessageId=='0100'){
	        
	        $JT0100 = new JT808_0100();
	        
	        $result = $JT0100->encodeBody($data16Array);
	        
	        $token = '';//鉴权码
	       
	        $info = $db->select('id,token,status')->from('device')->where('phone= :phone')->bindValues(array('phone'=>$equipmentNumber))->row();
	        
	        if(empty($info)){
	            
	            $token= $JT808->createToken();   //鉴权码
	            
	            // 插入
	            $db->insert('device')->cols(array(
	                'phone'        =>$equipmentNumber,
	                'device_type'  =>$result['deviceType'],
	                'device_id'    =>$result['deviceId'],
	                'color'        =>'M',
	                'car_mark'     =>$result['carMark'],
	                'status'       =>1,
	                'token'        =>$token,
	                'active_time'  =>$now,
	                'ctime'        =>$now))->query();
	        }
	        else{
	            //终端已被注册
	            $ret = '03';
	            
	            /*
	            if($info['status']==1){
	                
	                $ret = '03';
	            }
	            else{
	                
	                $token= $JT808->createToken();   //鉴权码
	                
	                //$db->update('device')->cols(array('status'=>1,'active_time'=>date('Y-m-d H:i:s'),'token'=>$token))->where('id='.$info['id'])->query();
	            }*/
	        }
	        
	        print_r($result);
	        
	        //发送给客户端
	        $sendClientData = $JT808->getResponseNotify($data16Array,$ret,$token);
	    }
	    //终端鉴权
	    elseif($MessageId=='0102'){
	        
	        $JT0102 = new JT808_0102();
	        
	        $result = $JT0102->encodeBody($data16Array);
	        
	        $info = $db->select('id,token,status')->from('device')->where('phone= :phone AND token = :token')->bindValues(array('phone'=>$equipmentNumber,'token'=>$result))->row();
	        
	        //没有对应的设备时
	        if(empty($info)){
	            //失败
	            $ret = '01';
	        }
	        else{
	            $ret = '00';
	            
	            $db->update('device')->cols(array('active_time'=>$now,'status'=>1))->where('id='.$info['id'])->query();
	        }
	        
	        //发送给客户端
	        $sendClientData = $JT808->getResponseNotify($data16Array,$ret);
	    }
	    //终端注销
	    elseif($MessageId=='0003'){
	        
	        //按楼下的意见，注销直接剔除
	        $db->delete('device')->where('phone='.$equipmentNumber)->query();
	        
	        //发送给客户端
	        $sendClientData = $JT808->getResponseNotify($data16Array,$ret);
	    }
	    //终端心跳
	    elseif($MessageId=='0002'){
	        
	        $db->update('device')->cols(array('active_time'=>$now,'status'=>1))->where('phone='.$equipmentNumber)->query();
	        
	        //发送给客户端
	        $sendClientData = $JT808->getResponseNotify($data16Array,$ret);
	    }
		//位置信息上报获取
		elseif ($MessageId == '0200' && $equipmentNumber) {
			//报警信息
			$AlarmMessage = $JT808->getAlarmMessage($data16Array, 13);
			//状态
			$status = $JT808->getPositionStatus($data16Array, 17);
			//经度
			$Latitude = $JT808->getLatitude($data16Array, 21, 'i');
			//纬度
			$Longitude = $JT808->getLongitude($data16Array, 25, 'i');
			//高度
			$Height = $JT808->getHeight($data16Array, 29);
			//速度
			$Speed = $JT808->getSpeed($data16Array, 31);
			//方向
			$Direction = $JT808->getDirection($data16Array, 33);
			//时间
			$Datetime = $JT808->getDatetime($data16Array, 35);
			if ($Latitude && $Longitude) {
				//执行你的逻辑
			}
			
			//发送给客户端
			$sendClientData = $JT808->getResponseNotify($data16Array,$ret);
		}
		
		
		$JT808->logWrite('sendClientData:'.bin2hex($sendClientData));
		
		$connection->send($sendClientData);
	}
};

// 运行worker
Worker::runAll();
